<script setup lang="ts">
import {onMounted, ref} from 'vue';
import type {UploadProps} from 'element-plus';
import {ElMessage} from 'element-plus';
import {Edit, Plus} from '@element-plus/icons-vue';
import {options} from '@/assets/administrative-division.ts';
import SideBar from "./components/SideBar.vue";
import {useUserStore} from "@/stores/userStore.ts";
import {UpdateUserDetailDTO, UserControllerService} from "../../../generated";
import {useRouter} from "vue-router";

const userProfile = ref<UpdateUserDetailDTO>({
  avatar: '',
  username: '',
  gender: 0,
  birthday: '',
  currentResidence: '',
  profile: '',
  website: '',
  github: '',
  school: '',
  company: '',
  position: '',
  tagList: []
});

const commonTags = [
  'Java',
  'Python',
  'C++',
  'JavaScript',
  'C',
  'MySQL',
  'PHP',
  'HTML',
  'Android',
  'CSS'
];

const locationValue = ref<string[]>([]);

let userStore = useUserStore();
let router = useRouter();

const handleAvatarSuccess: UploadProps['onSuccess'] = (response) => {
  userProfile.value.avatar = response.data;
  ElMessage.success('头像上传成功');
};

const beforeAvatarUpload: UploadProps['beforeUpload'] = (file) => {
  const isJPG = file.type === 'image/jpeg' || file.type === 'image/png';
  const isLt2M = file.size / 1024 / 1024 < 2;

  if (!isJPG) {
    ElMessage.error('头像只能是 JPG 或 PNG 格式!');
  }
  if (!isLt2M) {
    ElMessage.error('头像大小不能超过 2MB!');
  }
  return isJPG && isLt2M;
};

const addCommonTag = (tag: string) => {
  if (!userProfile.value.tagList) {
    userProfile.value.tagList = [];
  }
  if (!userProfile.value.tagList.includes(tag) && userProfile.value.tagList.length < 10) {
    userProfile.value.tagList.push(tag);
  }
};

const handleLocationChange = (value: string[]) => {
  if (value && value.length) {
    locationValue.value = value;
    userProfile.value.currentResidence = value.join('/');
  } else {
    locationValue.value = [];
    userProfile.value.currentResidence = '';
  }
};

const locationProps = {
  expandTrigger: 'hover' as const,
  multiple: false,
  checkStrictly: false,
  value: 'name',
  label: 'name',
};

const saveProfile = async () => {
  let res = await UserControllerService.updateUserInfoUsingPost({
    ...userProfile.value,
    userId: userStore.loginUser.id
  });
  if (res.code === 0 && res.data) {
    ElMessage.success('更新成功');
    await router.push('/profile/' + userStore.loginUser.account)
  } else {
    ElMessage.error(res.message);
  }
};

const fetchUserDetail = async () => {
  let res = await UserControllerService.getUserDetailUsingGet();
  if (res.code === 0 && res.data) {
    userProfile.value = res.data as UpdateUserDetailDTO;
    if (res.data.currentResidence) {
      locationValue.value = res.data.currentResidence.split('/')
    }
  } else {
    ElMessage.error(res.message)
  }
}

onMounted(() => {
  fetchUserDetail()
})
</script>

<template>
  <div class="profile-container">
    <SideBar/>
    <div class="profile-edit">
      <el-form :model="userProfile" label-position="top" label-width="auto">
        <el-form-item>
          <div class="avatar-container">
            <el-upload
                class="avatar-uploader"
                action="http://localhost:8080/api/files/upload"
                :show-file-list="false"
                :on-success="handleAvatarSuccess"
                :before-upload="beforeAvatarUpload"
            >
              <div class="avatar-wrapper">
                <img v-if="userProfile.avatar" :src="userProfile.avatar" class="avatar"/>
                <el-icon v-else class="avatar-uploader-icon">
                  <Plus/>
                </el-icon>
                <div class="avatar-edit-icon">
                  <el-icon>
                    <Edit/>
                  </el-icon>
                </div>
              </div>
            </el-upload>
          </div>
        </el-form-item>

        <div class="form-row">
          <el-form-item label="昵称" class="form-item-half">
            <el-input v-model="userProfile.username" placeholder="请输入昵称"/>
          </el-form-item>

          <el-form-item label="性别" class="form-item-half">
            <div class="gender-select">
              <div
                  class="gender-option male"
                  :class="{ active: userProfile.gender === 0 }"
                  @click="userProfile.gender = 0"
              >
                男性
              </div>
              <div
                  class="gender-option female"
                  :class="{ active: userProfile.gender === 1 }"
                  @click="userProfile.gender = 1"
              >
                女性
              </div>
            </div>
          </el-form-item>
        </div>

        <div class="form-row">
          <el-form-item label="生日" class="form-item-half">
            <el-date-picker
                v-model="userProfile.birthday"
                type="date"
                placeholder="选择生日"
                format="YYYY-MM-DD"
                style="width: 100%"
            />
          </el-form-item>

          <el-form-item label="现居地" class="form-item-half">
            <el-cascader
                v-model="locationValue"
                :options="options"
                :props="locationProps"
                placeholder="请选择现居地"
                filterable
                clearable
                @change="handleLocationChange"
            />
          </el-form-item>
        </div>

        <el-form-item label="个人介绍">
          <el-input
              v-model="userProfile.profile"
              type="textarea"
              :rows="4"
              placeholder="介绍一下自己吧"
              maxlength="100"
              show-word-limit
          />
        </el-form-item>

        <el-form-item label="个人网站">
          <el-input v-model="userProfile.website" placeholder="请输入个人网站地址"/>
        </el-form-item>

        <el-form-item label="GitHub">
          <el-input v-model="userProfile.github" placeholder="请输入GitHub用户名"/>
        </el-form-item>

        <el-form-item label="就读学校">
          <el-input v-model="userProfile.school" placeholder="请输入学校名称"/>
        </el-form-item>

        <div class="form-row">
          <el-form-item label="所在公司" class="form-item-half">
            <el-input v-model="userProfile.company" placeholder="请输入公司名称"/>
          </el-form-item>

          <el-form-item label="职位" class="form-item-half">
            <el-input v-model="userProfile.position" placeholder="请输入职位"/>
          </el-form-item>
        </div>

        <el-form-item label="技能标签">
          <el-input-tag
              v-model="userProfile.tagList"
              :max="10"
              placeholder="你的技能标签"
          >
            <template #suffix>
              <span class="tag-count">{{ userProfile.tagList?.length || 0 }}/10</span>
            </template>
          </el-input-tag>
        </el-form-item>
        <el-form-item label="常用标签">
          <div class="common-tag-list">
            <el-tag
                v-for="tag in commonTags"
                :key="tag"
                class="common-tag"
                @click="addCommonTag(tag)"
                :disabled="userProfile.tagList?.includes(tag)"
            >
              {{ tag }}
            </el-tag>
          </div>
        </el-form-item>
      </el-form>

      <div class="save-button-container">
        <el-button type="success" @click="saveProfile">保存</el-button>
      </div>
    </div>
  </div>
</template>

<style scoped>
.profile-container {
  display: flex;
  gap: 20px;
  max-width: 1000px;
  margin: 20px auto;
  padding: 0 20px;
}

.profile-edit {
  flex: 1;
  background-color: #fff;
  padding: 20px;
  border-radius: 8px;
  max-width: none;
  margin: 0;
}

.avatar-container {
  display: flex;
  justify-content: center;
  width: 100%;
}

.avatar-wrapper {
  position: relative;
  width: 100px;
  height: 100px;
  border-radius: 50%;
  overflow: visible;
}

.avatar {
  width: 100%;
  height: 100%;
  display: block;
  object-fit: cover;
  border-radius: 50%;
}

.avatar-uploader {
  border: none;
  cursor: pointer;
  position: relative;
  overflow: visible;
  transition: var(--el-transition-duration-fast);
}

:deep(.el-upload) {
  border: none;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 100px;
  height: 100px;
  text-align: center;
  line-height: 100px;
  border: 1px dashed var(--el-border-color);
  border-radius: 50%;
}

.avatar-edit-icon {
  position: absolute;
  right: -2px;
  bottom: -2px;
  width: 28px;
  height: 28px;
  border-radius: 50%;
  background-color: var(--el-color-primary);
  display: flex;
  align-items: center;
  justify-content: center;
  color: white;
  font-size: 14px;
  cursor: pointer;
  transition: all 0.3s;
  border: 2px solid white;
  transform-origin: center;
}

.avatar-wrapper:hover .avatar-edit-icon {
  transform: scale(1.05);
}

.form-row {
  display: flex;
  gap: 20px;
  margin-bottom: 5px;
}

.form-item-half {
  flex: 1;
  margin-bottom: 22px;
}

.form-item-half :deep(.el-form-item__content) {
  width: 100%;
}

.form-item-half :deep(.el-form-item__label) {
  padding-bottom: 8px;
}

:deep(.el-form-item__label) {
  line-height: 1.5;
  font-size: 14px;
  color: var(--el-text-color-regular);
}

.gender-select {
  display: flex;
  width: 100%;
  height: 32px;
  gap: 8px;
  border-radius: 0.5rem;
  overflow: visible;
  border: none;
}

.gender-option {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  transition: all 0.3s;
  font-size: 14px;
  user-select: none;
  border-radius: 0.5rem;
  height: 40px;
  color: #262626bf;
  background-color: #00000008;
}

.gender-option:first-child {
  border-right: 1px solid var(--el-border-color);
}

.gender-option.male.active {
  background-color: #007aff14;
  color: rgb(0 122 255);
}

.gender-option.female.active {
  background-color: #ff74d01f;
  color: rgb(255 116 208);
}

.gender-option:hover:not(.active) {
  background-color: var(--el-fill-color-light);
}

:deep(.el-input__wrapper) {
  height: 28px;
  padding: 5px 11px;
  border-radius: .375rem;
  color: #262626bf;
  background-color: #00000008;
  box-shadow: none !important;
  transition: all 0.3s;
  border: 1px solid transparent;
}

:deep(.el-input__wrapper.is-focus) {
  box-shadow: 0 0 0 2px #007aff14 !important;
  background-color: white;
  border: 1px solid rgb(0 122 255);
  padding: 5px 11px;
}

:deep(.el-textarea__inner) {
  border-radius: .375rem;
  color: #262626bf;
  background-color: #00000008;
  box-shadow: none !important;
  border: 1px solid transparent;
  transition: all 0.3s;
  padding: 5px 11px;
}

:deep(.el-textarea__inner:focus) {
  background-color: white;
  box-shadow: 0 0 0 2px #007aff14 !important;
  border: 1px solid rgb(0 122 255);
  padding: 5px 11px;
}

:deep(.el-input-tag__wrapper) {
  height: 40px;
  border-radius: .375rem;
  background-color: #00000008;
  color: #262626bf;
  box-shadow: none !important;
  border: 1px solid transparent;
  transition: all 0.3s;
}

:deep(.el-input-tag__wrapper.is-focus) {
  box-shadow: 0 0 0 2px #007aff14 !important;
  background-color: white;
  border: 1px solid rgb(0 122 255);
  padding: 5px 11px;
}

:deep(.el-tag) {
  background-color: #000a200d;
  border-radius: 9999px;
}

.tag-count {
  color: #8c8c8c;
  font-size: 12px;
  margin-right: 4px;
}

:deep(.el-input-tag__suffix) {
  display: flex;
  align-items: center;
}

.common-tag-list {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
}

.common-tag {
  cursor: pointer;
  transition: all 0.3s;
  background-color: #000a200d;
  border-radius: 9999px;
}

.common-tag:hover {
  background-color: #000a201a;
}

:deep(.el-tag__content) {
  color: #909399;
}

.save-button-container {
  display: flex;
  justify-content: flex-end;
}

:deep(.el-button--success) {
  --el-button-bg-color: #10b981;
  --el-button-border-color: #10b981;
  --el-button-hover-bg-color: #059669;
  --el-button-hover-border-color: #059669;
}

:deep(.el-cascader) {
  width: 100%;
}

:deep(.el-cascader .el-input__wrapper) {
  background-color: #00000008;
}

:deep(.el-cascader .el-input__wrapper.is-focus) {
  background-color: white;
}

:deep(.el-divider) {
  margin: 0;
}
</style>